package com.ca.ridersclubapplication.adapter;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Build;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.RecyclerView;

import com.ca.ridersclubapplication.ChatActivity;
import com.ca.ridersclubapplication.R;
import com.ca.ridersclubapplication.data.DataHandler;
import com.ca.ridersclubapplication.request.FileRequester;
import com.ca.ridersclubapplication.request.dto.AccountDto;
import com.ca.ridersclubapplication.request.dto.ChatMessageDto;
import com.ca.ridersclubapplication.util.ImageUtils;
import com.ca.ridersclubapplication.util.TimeUtils;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BubbleAdapter extends RecyclerView.Adapter<BubbleAdapter.BubbleHolder> {

    private final Activity activity;
    private List<ChatMessageDto> list;

    public BubbleAdapter(Activity activity, List<ChatMessageDto> list) {
        this.activity = activity;
        this.list = list == null ? new ArrayList<>() : list;
    }

    @NonNull
    @Override
    public BubbleHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.bubble_item_layout, parent, false);
        return new BubbleHolder(view);
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public void onBindViewHolder(@NonNull BubbleHolder holder, int position) {

        ChatMessageDto dto = list.get(position);

        //  判断消息类型（左、右）
        Long targetId = dto.getTargetId();
        Long accountId = DataHandler.getToken(activity).getId();
        if (!targetId.equals(accountId)) {
            //  如果信息来源与自己
            holder.leftCL.setVisibility(View.GONE);
            holder.rightCL.setVisibility(View.VISIBLE);
            ImageUtils.loadCircleImage(activity, FileRequester.HEADER_BY_ID_BASE_URL + accountId, holder.rightHeaderView);
            holder.rightView.setText(dto.getContent());
        }
        else {
           //   消息来源与对方
            holder.rightCL.setVisibility(View.GONE);
            holder.leftCL.setVisibility(View.VISIBLE);
            ImageUtils.loadCircleImage(activity, FileRequester.HEADER_BY_ID_BASE_URL + dto.getSourceId(), holder.leftHeaderView);
            holder.leftView.setText(dto.getContent());
        }

        //  判断是否显示时间
        if (position == getItemCount() - 1) {
            //  如果为最后一条消息则显示时间
            holder.centerView.setText(TimeUtils.parseShowDateTime(dto.getTime()));
            holder.centerView.setVisibility(View.VISIBLE);
            return;
        }
        //  否则显示时间的判断依据下一条消息的时间
        ChatMessageDto nextDto = list.get(position + 1);
        LocalDateTime time = LocalDateTime.parse(dto.getTime().replace(" ", "T"));
        LocalDateTime nextTime = LocalDateTime.parse(nextDto.getTime().replace(" ", "T"));
        Duration between = Duration.between(time, nextTime);
        if (between.toMinutes() > 5 || between.toMinutes() < -5) {
            //  超过五分钟则显示时间
            holder.centerView.setText(TimeUtils.parseShowDateTime(dto.getTime()));
            holder.centerView.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    public List<ChatMessageDto> getList() {
        return list;
    }

    @SuppressLint("NotifyDataSetChanged")
    public void setList(List<ChatMessageDto> list) {
        if (list == null) {
            list = new ArrayList<>();
        }

        if (!this.list.equals(list)) {
            this.list = list;
        }

        notifyDataSetChanged();
    }

    @SuppressLint("NotifyDataSetChanged")
    public void appendListToTop(List<ChatMessageDto> list) {

        if (list == null) {
            return;
        }
        this.list.addAll(list);
        notifyDataSetChanged();
    }

    @SuppressLint("NotifyDataSetChanged")
    public void appendListToBottom(List<ChatMessageDto> list) {

        if (list == null || list.size() == 0) {
            return;
        }

        this.list.addAll(0 ,list);
        notifyDataSetChanged();

        if (ChatActivity.canAutoToBottom) {
            Log.e("AppendToBottom", "...");
        }
    }

    public static class BubbleHolder extends RecyclerView.ViewHolder {

        public ConstraintLayout leftCL;
        public ConstraintLayout rightCL;

        public ImageView leftHeaderView;
        public ImageView rightHeaderView;

        public TextView leftView;
        public TextView rightView;
        public TextView centerView;

        public BubbleHolder(@NonNull View itemView) {
            super(itemView);

            leftHeaderView = itemView.findViewById(R.id.iv_left);
            rightHeaderView = itemView.findViewById(R.id.iv_right);

            leftView = itemView.findViewById(R.id.tv_left);
            rightView = itemView.findViewById(R.id.tv_right);
            centerView = itemView.findViewById(R.id.tv_center);

            leftCL = itemView.findViewById(R.id.cl_left);
            rightCL = itemView.findViewById(R.id.cl_right);
        }
    }
}
